const { userNotExists, userInputError } = require("../constant/error.type");
const { findUser } = require("../service/user.service");
const md5Password = require("../utils/encrypt");

/**
 * 验证用户登录
 */
async function verifyUserLogin(ctx, next) {
  const user = ctx.request.body;
  // 1.查询数据库判断用户是否存在
  const isExistUser = await findUser(user.name);
  if (isExistUser.length == 0) {
    return ctx.app.emit("error", userNotExists, ctx);
  }
  //2.判断用户密码是否一致
  if (
    isExistUser[0].password.toLocaleLowerCase() != md5Password(user.password)
  ) {
    return ctx.app.emit("error", userInputError, ctx);
  }
  //3.保存用户在全局(给后续颁发token操作)
  ctx.user = isExistUser[0];
  await next();
}
module.exports = {
  verifyUserLogin,
};
